﻿using DotNetty.Handlers.Logging;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AiMei.Redis.Core
{
    public class RedisConnect:IDisposable
    {
        private string _ip { get; set; }
        private int _port { get; set; }
        public IChannel clientChannel { get; set; }
        private MultithreadEventLoopGroup group;
        public RedisConnect(string ip, int port)
        {
            _ip = ip;
            _port = port;
            RunClientAsync().Wait();
        }
        async Task RunClientAsync()
        {

            group = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                    .Group(group)
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true)
                    .Handler(new DotNetty.Handlers.Logging.LoggingHandler(LogLevel.DEBUG))
                    .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        pipeline.AddLast(new RedisDecoder());
                        pipeline.AddLast(new RedisEncoder());
                        pipeline.AddLast(new RedisHandle());


                    }));

                clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(_ip), _port));

                //await clientChannel.CloseAsync();
            }
            finally
            {
                //await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }

        public async Task DisposeAsync()
        {
            await clientChannel.DisconnectAsync();
            await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
        }

        public void Dispose()
        {
            DisposeAsync().Wait();
        }
    }
}
